package com.sls.web.manager.action.game;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;

import com.sls.web.manager.action.SuperAction;
import com.sls.web.manager.common.Constants;
import com.sls.web.manager.execption.ManagerException;
import com.sls.web.manager.game.pojo.SnnsGoodsInfo;
import com.sls.web.manager.game.querybean.SnnsProductQuery;
import com.sls.web.manager.game.service.SnnsGoodsService;
import com.sls.web.manager.page.Pagination;

/**
 * @description 7996供货商原始商品管理
 * @author Wangxuegang
 * @date 2013-4-23
 */
@InterceptorRefs({
		@InterceptorRef(value = "defaultStack", params = { "maximumSize",
				"2048000", "allowedTypes",
				"text/plain,application/excel,application/vnd.ms-excel" }),
		@InterceptorRef(value = "defalutStackSet") })
public class SnnsGoodsAction extends SuperAction {

	private static final long serialVersionUID = 1L;

	private String productExcelFileName;// 获取上传文件名称

	private File productExcel;// 获取上传文件

	private SnnsProductQuery snnsQuery;

	private String product_id;

	private String product_name;

	private String product_parvalue;

	private String product_price;

	private String insert_time;

	private String modify_time;

	private String isAudit;

	@Resource(name = "snnsGoodsService")
	private SnnsGoodsService snnsGoodsService;

	private int priceRatio;

	private String supplierId;

	private Pagination<?> page;

	private SnnsGoodsInfo snnsGoodsInfo;

	private String proId;

	/**
	 * 保存产品信息
	 * 
	 * @return
	 * @throws Exception
	 */
	public String save() throws Exception {
		try {
			snnsGoodsService.save(snnsGoodsInfo, getCurrentOperator());
			redirectionUrl = "snns_goods!list.htm";
		} catch (ManagerException e) {
			flag = false;
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	/**
	 * 记录修改
	 * 
	 * @return
	 * @throws Exception
	 */
	public String edit() throws Exception {
		try {
			snnsGoodsService.update(snnsGoodsInfo, getCurrentOperator());
			if (snnsQuery == null) {
				snnsQuery = new SnnsProductQuery();
				snnsQuery.setCurrentPage(Constants.INIT_CURRENTPAGE);
				snnsQuery.setPageSize(Constants.INIT_PAGESIZE);
			}
			if (StringUtils.isNotEmpty(proId)) {
				snnsQuery.setProduct_id(proId);
			}
			if (StringUtils.isNotEmpty(product_name)) {
				snnsQuery.setProduct_name(product_name);
			}
			if (StringUtils.isNotEmpty(isAudit)) {
				snnsQuery.setIsAudit(isAudit);
			}
		} catch (ManagerException e) {
			addActionError(e.getMessage());
		}
		return list();
	}

	/**
	 * 记录修改页面跳转
	 * 
	 * @return
	 * @throws Exception
	 */
	public String toEdit() throws Exception {
		try {
			snnsGoodsInfo = snnsGoodsService.queryByProductId(product_id,
					getCurrentOperator());
		} catch (ManagerException e) {
			addActionError(e.getMessage());
		}
		return INPUT;
	}

	/**
	 * 批量上架
	 * 
	 * @return
	 * @throws Exception
	 */
	public String batchOnline() throws Exception {
		try {
			snnsGoodsService.batchOnline("1", getCurrentOperator());
			redirectionUrl = "supply_snns!list.htm";
		} catch (ManagerException e) {
			flag = false;
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	/**
	 * 批量下架
	 * 
	 * @return
	 * @throws Exception
	 */
	public String batchOffline() throws Exception {
		try {
			this.snnsGoodsService.batchOnline("0", getCurrentOperator());
			redirectionUrl = "supply_snns!list.htm";
		} catch (ManagerException e) {
			flag = false;
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	/**
	 * 商品批量审核
	 * 
	 * @return
	 * @throws Exception
	 */
	public String audit() throws Exception {
		try {
			this.snnsGoodsService.confirmAudit(supplierId, priceRatio,
					getCurrentOperator());
			redirectionUrl = "supply_snns!list.htm";
		} catch (ManagerException e) {
			flag = false;
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	/**
	 * 导入产品excel文件
	 * 
	 * @return
	 * @throws Exception
	 */
	public String importProductFile() throws Exception {
		if (StringUtils.isEmpty(productExcelFileName)) {
			flag = false;
			addActionError("请选择要导入的文件!");
			return SUCCESS;
		}
		if (!productExcelFileName.endsWith(".xls")
				&& !productExcelFileName.endsWith(".xlsx")) {
			flag = false;
			addActionError("文件类型有误!<br>必须为excel文件!");
			return SUCCESS;
		}
		InputStream is = null;
		try {
			is = new FileInputStream(productExcel);
		} catch (FileNotFoundException e1) {
			addActionError(e1.getMessage());
		}
		List<SnnsGoodsInfo> list = null;
		try {
			if (is != null) {
				if (productExcelFileName.endsWith(".xls")) {
					list = this.extractListFromXLS2003(is);
				} else if (productExcelFileName.endsWith(".xlsx")) {
					list = this.extractListFromXLS2007(is);
				}
			}
		} catch (IOException e) {
			addActionError(e.getMessage());
		}
		String message = "";
		if (list != null && !list.isEmpty()) {
			for (SnnsGoodsInfo snnsInfo : list) {
				if (snnsInfo != null) {
					try {
						this.snnsGoodsService.save(snnsInfo,
								getCurrentOperator());
					} catch (ManagerException e) {
						message += snnsInfo.getProduct_id() + ","
								+ e.getMessage() + "<br>";
						continue;
					}
				}
			}
		}
		if (StringUtils.isNotEmpty(message)) {
			flag = false;
			addActionError(message);
		}
		this.redirectionUrl = "supply_snns!list.htm";
		return SUCCESS;
	}

	/**
	 * 添加产品
	 * 
	 * @return
	 */
	public String addInfo() {
		return INPUT;
	}

	/**
	 * 产品列表显示
	 * 
	 * @return
	 * @throws Exception
	 */
	public String list() throws Exception {
		if (snnsQuery == null) {
			snnsQuery = new SnnsProductQuery();
			snnsQuery.setCurrentPage(Constants.INIT_CURRENTPAGE);
			snnsQuery.setPageSize(Constants.INIT_PAGESIZE);
		}
		try {
			page = this.snnsGoodsService.querySnnsProduct(snnsQuery,
					getCurrentOperator());
		} catch (ManagerException e) {
			addActionError(e.getMessage());
		}
		return LIST;
	}

	/**
	 * 解析excel2003文件
	 * 
	 * @param is
	 * @return
	 * @throws IOException
	 */
	private List<SnnsGoodsInfo> extractListFromXLS2003(InputStream is)
			throws IOException {
		List<SnnsGoodsInfo> list = new ArrayList<SnnsGoodsInfo>();
		SnnsGoodsInfo snnsInfo = null;
		HSSFWorkbook workbook = new HSSFWorkbook(is); // 创建对Excel工作簿文件的引用
		for (int numSheets = 0; numSheets < workbook.getNumberOfSheets(); numSheets++) {
			if (null != workbook.getSheetAt(numSheets)) {
				HSSFSheet aSheet = workbook.getSheetAt(numSheets); // 获得一个sheet
				for (int rowNumOfSheet = 1; rowNumOfSheet <= aSheet
						.getLastRowNum(); rowNumOfSheet++) {
					if (null != aSheet.getRow(rowNumOfSheet)) {
						snnsInfo = new SnnsGoodsInfo();
						List<String> cellList = new ArrayList<String>();
						HSSFRow aRow = aSheet.getRow(rowNumOfSheet); // 获得一行
						for (int cellNumOfRow = 0; cellNumOfRow <= aRow
								.getLastCellNum(); cellNumOfRow++) {
							if (null != aRow.getCell(cellNumOfRow)) {
								HSSFCell aCell = aRow.getCell(cellNumOfRow); // 获得列值
								if (aCell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
									double parvalue = aCell
											.getNumericCellValue();
									cellList.add(String.valueOf(parvalue));
								} else if (aCell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
									boolean flag = aCell.getBooleanCellValue();
									cellList.add(String.valueOf(flag));
								} else {
									cellList.add(aCell.getStringCellValue());
								}

								if (cellList.size() > 0) {
									snnsInfo.setProduct_id(cellList.get(0));
								}
								if (cellList.size() > 1) {
									snnsInfo.setProduct_name(cellList.get(1));
								}
								if (cellList.size() > 2) {
									snnsInfo.setProduct_parvalue(cellList
											.get(2));
								}
								if (cellList.size() > 3) {
									snnsInfo.setProduct_price(cellList.get(3));
								}
							}
						}

					}
					list.add(snnsInfo);
				}
			}
		}
		return list;
	}

	/**
	 * 解析excel2007文件
	 * 
	 * @param is
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	private List<SnnsGoodsInfo> extractListFromXLS2007(InputStream is)
			throws IOException {
		List<SnnsGoodsInfo> list = new ArrayList<SnnsGoodsInfo>();
		SnnsGoodsInfo snnsInfo = null;
		// 构造 XSSFWorkbook 对象，strPath
		// 传入文件路径
		XSSFWorkbook xwb = new XSSFWorkbook(is);
		// 循环工作表Sheet
		for (int numSheet = 0; numSheet < xwb.getNumberOfSheets(); numSheet++) {
			XSSFSheet xSheet = xwb.getSheetAt(numSheet);
			if (xSheet == null) {
				continue;
			}
			// 循环行Row
			for (int rowNum = 1; rowNum <= xSheet.getLastRowNum(); rowNum++) {
				snnsInfo = new SnnsGoodsInfo();
				XSSFRow xRow = xSheet.getRow(rowNum);
				if (xRow == null) {
					continue;
				}
				List<String> cellList = new ArrayList<String>();
				// 循环列Cell
				for (int cellNum = 0; cellNum <= xRow.getLastCellNum(); cellNum++) {
					XSSFCell xCell = xRow.getCell(cellNum);

					if (xCell == null) {
						continue;
					}
					if (xCell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {
						boolean flag = xCell.getBooleanCellValue();
						cellList.add(String.valueOf(flag));
					} else if (xCell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
						double parvalue = xCell.getNumericCellValue();
						cellList.add(String.valueOf(parvalue));
					} else {
						cellList.add(xCell.getStringCellValue());
					}
					if (cellList.size() > 0) {
						snnsInfo.setProduct_id(cellList.get(0));
					}
					if (cellList.size() > 1) {
						snnsInfo.setProduct_name(cellList.get(1));
					}
					if (cellList.size() > 2) {
						snnsInfo.setProduct_parvalue(cellList.get(2));
					}
					if (cellList.size() > 3) {
						snnsInfo.setProduct_price(cellList.get(3));
					}
				}
				list.add(snnsInfo);
			}
		}
		return list;
	}

	// ----------------------------------------------------

	public String getProductExcelFileName() {
		return productExcelFileName;
	}

	public void setProductExcelFileName(String productExcelFileName) {
		this.productExcelFileName = productExcelFileName;
	}

	public File getProductExcel() {
		return productExcel;
	}

	public void setProductExcel(File productExcel) {
		this.productExcel = productExcel;
	}

	public SnnsProductQuery getSnnsQuery() {
		return snnsQuery;
	}

	public void setSnnsQuery(SnnsProductQuery snnsQuery) {
		this.snnsQuery = snnsQuery;
	}

	public String getProduct_id() {
		return product_id;
	}

	public void setProduct_id(String product_id) {
		this.product_id = product_id;
	}

	public String getProduct_name() {
		return product_name;
	}

	public void setProduct_name(String product_name) {
		this.product_name = product_name;
	}

	public String getProduct_parvalue() {
		return product_parvalue;
	}

	public void setProduct_parvalue(String product_parvalue) {
		this.product_parvalue = product_parvalue;
	}

	public String getProduct_price() {
		return product_price;
	}

	public void setProduct_price(String product_price) {
		this.product_price = product_price;
	}

	public String getInsert_time() {
		return insert_time;
	}

	public void setInsert_time(String insert_time) {
		this.insert_time = insert_time;
	}

	public String getModify_time() {
		return modify_time;
	}

	public void setModify_time(String modify_time) {
		this.modify_time = modify_time;
	}

	public String getIsAudit() {
		return isAudit;
	}

	public void setIsAudit(String isAudit) {
		this.isAudit = isAudit;
	}

	public int getPriceRatio() {
		return priceRatio;
	}

	public void setPriceRatio(int priceRatio) {
		this.priceRatio = priceRatio;
	}

	public String getSupplierId() {
		return supplierId;
	}

	public void setSupplierId(String supplierId) {
		this.supplierId = supplierId;
	}

	public Pagination<?> getPage() {
		return page;
	}

	public void setPage(Pagination<?> page) {
		this.page = page;
	}

	public SnnsGoodsInfo getSnnsGoodsInfo() {
		return snnsGoodsInfo;
	}

	public void setSnnsGoodsInfo(SnnsGoodsInfo snnsGoodsInfo) {
		this.snnsGoodsInfo = snnsGoodsInfo;
	}

	public String getProId() {
		return proId;
	}

	public void setProId(String proId) {
		this.proId = proId;
	}

}
